package com.lb.sentinelproject.exception;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lb.sentinelproject.utils.R;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义sentinel异常返回信息
 * @author user
 */
@Component
public class CustomUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request,
                        HttpServletResponse response,
                        BlockException e) throws IOException {
        R r = null;
        // BlockException 异常接口，其子类为Sentinel五种规则异常的实现类
        // AuthorityException 授权异常
        // DegradeException 降级异常
        // FlowException 限流异常
        // ParamFlowException 参数限流异常
        // SystemBlockException 系统负载异常
        if (e instanceof FlowException) {
            r = R.error(100, "访问速度过快");
        } else if (e instanceof DegradeException) {
            r = R.error(100, "接口已被降级，暂时无法访问");
        } else if (e instanceof AuthorityException) {
            r = R.error(100, "无权访问");
        } else if (e instanceof ParamFlowException) {
            r = R.error(100, "热点参数限流了");
        } else if (e instanceof SystemBlockException) {
            r = R.error(100, "系统靠不住了，稍等吧");
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-type","application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(response.getWriter(), r);
    }
}